import configparser
import math
import time
from sqlalchemy import Column, String, create_engine, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import requests

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36",
    "cookie": ""
}

# 创建对象的基类:
Base = declarative_base()


class up_fans(Base):
    # 表的名字:
    __tablename__ = 'up_fans'

    # 表的结构:

    mid = Column(Integer, primary_key=True)
    down_time = Column(Integer)
    fans = Column(Integer)


def up_get_fans(cookie, mid):
    url = "http://api.bilibili.com/x/web-interface/card?mid={}"
    headers['cookie'] = cookie
    res = requests.get(url.format(mid), headers=headers)
    res = res.json()
    if res.get("code") == 0:
        # print(res.get("data").get("card").get("fans"))
        engine = create_engine("mysql+pymysql://root:Aa380562113.@192.168.2.8:3306/bilibili?charset=utf8")
        DBSession = sessionmaker(bind=engine)
        session = DBSession()
        new_up_fans = up_fans(mid=mid,
                              down_time=time.time(),
                              fans=res.get("data").get("card").get("fans")
                              )
        session.add(new_up_fans)
        session.commit()
        session.close()


def config():
    ck = []
    cp = configparser.RawConfigParser()
    cp.read('/root/bilibili/config.ini')
    # ck.append(cp.get('bilibili', 'cookie1'))
    # ck.append(cp.get('bilibili', 'cookie2'))
    ck.append(cp.get('bilibili', 'cookie3'))
    # up_list = cp.get('up_list', 'up_list')

    return ck


if __name__ == '__main__':
    cookie = config()[0]
    up_get_fans(cookie, 903059)
